<template>
  <div
    class="hello"
    style="
      width: 100%;
      display: flex;
      align-item: center;
      justify-content: center;
      margin-top: 50px;
      flex-direction: column;
    "
  >
    <section v-show="status === 'error'">{{ message }}</section>
    <section v-show="status === 'loading'">loading</section>
    <section
      v-show="status === 'successed'"
      style="
        width: 100%;
        display: flex;
        align-item: center;
        justify-content: center;
        flex-direction: column;
      "
    >
      <span
        >短链接 <a :href="shortUrl" target="__blank">{{ shortUrl }}</a></span
      >
      <span>二维码：<i id="qrcode" ref="qrcode" /></span>
    </section>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
// const QRCode: any = require("qrcodejs");
import QRCode from "QRCode"

interface Configs {
  message: string;
  status: boolean;
  link: string;
}

@Component({
  components: {},
})
export default class ResultBox extends Vue {
  // data
  public message: string = "";
  public status: string = "";
  public longUrl: string = "";
  public shortUrl: string = "";
  $bus: any;

   mounted(): void {
    this.init();
  }

  init(): void {
    this.message = "";
    this.$bus.$on("sendLongUrl", (config: Configs): any => {
      if (config.status) {
        this.longUrl = config.link;
        this.requestShortUrl();
      } else {
        this.status = "error";
        this.message = config.message;
      }
    });
  }
  requestShortUrl(): void {
    this.status = "loading";
    const qrcode: any = this.$refs.qrcode;
    qrcode.innerHTML = "";
    fetch("http://www.ggb.com:8000/api/url/shorten", {
      method: "post",
      headers: {
        "Content-type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        longUrl: this.longUrl,
      }),
    })
      .then((res: any): void => res.json())
      .then((res: any): void => {
        this.shortUrl = res.shortUrl;
        this.status = "successed";
        this.qrcode();
      });
  }
  qrcode(): void {
    new QRCode(this.$refs.qrcode, this.shortUrl);
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
canvas {
  width: 100px !important;
  height: 100px !important;
}
canvas img {
  width: 100px !important;
  height: 100px !important;
  display: none !important;
}
</style>
